/*
 * @Author: yaoling 1871883713@qq.com
 * @Date: 2022-10-25 14:39:17
 * @LastEditors: yaoling 1871883713@qq.com
 * @LastEditTime: 2022-12-01 15:34:39
 * @FilePath: \company-world\src\utils\bus.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
type BusClass = {
  emit: (name: string) => void
  on: (name: string, callback: Function) => void
  off: (name: string) => void
}
// 定义多种参数类型
type PramsKey = string | number | symbol
type List = {
  [key: PramsKey]: Array<Function>
}
class Bus implements BusClass {
  list: List
  constructor() {
    this.list = {}
  }
  // 发布事件,...args解构多个参数
  emit(name: string, ...args: Array<any>) {
    let evnentName: Array<Function> = this.list[name]
    evnentName?.forEach((fn) => {
      fn.apply(this, args)
    })
  }
  // 接收事件
  on(name: string, callback: Function) {
    let fn: Array<Function> = this.list[name] || []
    fn.push(callback)
    this.list[name] = fn
  }
  // 取消事件
  off(name: string) {
    if (this.list[name]) {
      delete this.list[name]
    }
  }
}
export default new Bus()

// import mitt from 'mitt'
// export default mitt()
